<?php

/**
 * This is the model class for table "tbl_dispatchdetails".
 *
 * The followings are the available columns in table 'tbl_dispatchdetails':
 * @property string $dispatch
 * @property string $custno
 * @property string $locno
 * @property string $billloc
 * @property string $calledinby
 * @property string $wonumber
 * @property string $ponumber
 * @property string $receiveddate
 * @property string $receivedtime
 * @property string $receivedby
 * @property string $priority
 * @property string $invoice
 * @property string $complete
 * @property double $techtime
 * @property string $multitech
 * @property string $serviceagrno
 * @property string $serviceagrper
 * @property string $taskno
 * @property string $skill
 * @property string $notes
 * @property integer $invoiced
 * @property string $jobnumber
 * @property string $sort
 * @property string $quotesource
 * @property integer $servicefreqflag
 * @property string $department
 * @property string $type
 */
class Dispatchdetails extends CActiveRecord
{
    public $locationModel;
	/**
	 * Returns the static model of the specified AR class.
	 * @return Dispatchdetails the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'tbl_dispatchdetails';
	}

    public function afterFind(){
        if($this->techtime == null){
            $this->techtime =0; 
        }
        return parent::afterFind();
    }

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('dispatch, custno, locno,calledinby,notes, receiveddate, receivedtime, receivedby', 'required'),
			array('billingtype,billparts,invoiced, servicefreqflag', 'numerical', 'integerOnly'=>true),
			array('techtime', 'numerical'),                        
			array('dispatch', 'length', 'max'=>15),
			array('custno, serviceagrno', 'length', 'max'=>7),
			array('locno, billloc', 'length', 'max'=>5),
			array('calledinby, receivedby', 'length', 'max'=>255),
			array('ponumber', 'length', 'max'=>20),
			array('wonumber', 'length', 'max'=>20),
			array('receivedtime', 'length', 'max'=>8),
			array('priority, sort', 'length', 'max'=>10),
			array('invoice, quotesource', 'length', 'max'=>10),
			array('multitech', 'length', 'max'=>1),
			array('serviceagrper, taskno, skill', 'length', 'max'=>2),
			array('jobnumber', 'length', 'max'=>50),
                        array('department','length','max'=>150),                       
                        array('receivedtime','date','format'=>'h:m:s','allowEmpty'=>true),
			array('complete, notes,billingtype,billnotes', 'safe'),
            array('ponumber','checkCustomerPo'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('dispatch, custno, locno, billloc, calledinby, ponumber, receiveddate, receivedtime, receivedby, priority, invoice, complete, techtime, multitech, serviceagrno, serviceagrper, taskno, skill, notes, invoiced, jobnumber, sort, quotesource, servicefreqflag', 'safe', 'on'=>'search'),
		);
	}
        function checkCustomerPo($attributes,$params){
            if($this->customer->requirepo!=NULL && $this->customer->requirepo==1 && ($this->ponumber==NULL)){
                $this->addError('ponumber', 'This company requires POs');
            }
            
        }
        
	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
                    'customer'=>array(self::BELONGS_TO,'Customers','custno'),
                    'lastestTask'=>array(self::HAS_ONE,'Dispatchtask','dispatch'),
                    'lastestTech'=>array(self::HAS_ONE,'DispatchTech','dispatch','order'=>'counter DESC'),
                    'equipments'=>array(self::HAS_MANY,'Dispatchequipment','dispatch'),
                    'invoiceList'=>array(self::HAS_MANY,'Invoice','dispatch'),
                  
		);
	}
    
    public function getLocation(){
        if($this->locationModel == null){
            $this->locationModel = Locations::model()->find('custno=:custno AND locno=:locno',array(
                'custno'=>$this->custno,
                'locno'=>$this->locno
            ));    
        }
        
        return $this->locationModel;
    }
    public function getTechnician(){
        return DispatchTech::model()->find('counter = max(counter) AND dispatch=:dispatch',array(
            'dispatch'=>$this->dispatch
        ));
    }
	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'dispatch' => 'Dispatch',
			'custno' => 'Customer number',
			'locno' => 'Location number',
			'billloc' => 'Billing Address',
			'calledinby' => 'Called In By',
			'ponumber' => 'P/O Number',
			'wonumber' => 'W/O Number',
			'receiveddate' => 'Date Received',
			'receivedtime' => 'Time Received',
			'receivedby' => 'Received By',
			'priority' => 'Priority',
			'invoice' => 'Invoice',
			'complete' => 'Complete',
			'techtime' => 'Techtime',
			'multitech' => 'Multitech',
			'serviceagrno' => 'Serviceagrno',
			'serviceagrper' => 'Serviceagrper',
			'taskno' => 'Taskno',
			'skill' => 'Skill Required',
			'notes' => 'Notes',
			'invoiced' => 'Invoice',
			'jobnumber' => 'Job',
			'sort' => 'Safes Sort',
			'quotesource' => 'Quotesource',
			'servicefreqflag' => 'Servicefreqflag',
            'type'=>'Type',
            'department'=>'Department',
            'billingtype'=>'Bill Type',
            'techtime'=>'Billable Time',
            'billparts'=>'Parts Billabled',
            'billnotes'=>'Bill Note'
		);
	}
        public function init() {

            parent::init();
            $this->dispatch=Counters::model()->getNextNumber('dispatch');
            $this->receivedby=Yii::app()->user->name;
            $this->receiveddate=DateUtil::getDefaultCurrentDateTime();
            $this->receivedtime=DateUtil::getDefaultCurrentTime();

        }
        public function beforeSave() {
            
            if($this->isNewRecord){
               
               
            }
            if($this->billingtype == 2){
                $this->invoice = 'Contract';
            }else if($this->billingtype == 3){
                $this->invoice ='Internal';
            }
            return parent::beforeSave();
        }
        public function afterSave() {
            if($this->isNewRecord){
                
                Counters::model()->saveNumber('dispatch');
                
                $model=new DispatchTech;
                $model->dispatch=$this->dispatch;
                $model->empno='0000';
                $model->status='Pending';
                $model->startdate=$this->receiveddate;
                $model->starttime=$this->receivedtime;
                $model->complete='N';
                
                $model->save();
            }
            
            return parent::afterSave();
        }
	
        
        public function getDepartmentList(){
            $types=Dispatchdepartments::model()->findAll();
            $rs =array();
            foreach($types as $type){
                $rs[$type->name]=$type->name;
            }
            return $rs;
        }
        public function getPriorityList(){
            return array(
                'Normal'=>'Normal',
                'Emergency'=>'Emergency',                
            );
        }
        public function setComplete(){
            $this->complete=DateUtil::getDefaultCurrentDateTime();
            $this->save();
        }
        public function isComplete(){
            return $this->complete!=NULL?true:false;
        }
        
        public function createDispatchByJob($jobid){
            $jobs=Jobs::model()->findByPk($jobid);
            /* @var $jobs Jobs */
            if($jobs!=NULL){
                $model=new Dispatchdetails;
                $model->custno=$jobs->custno;
                $model->locno=$jobs->locno;
                $model->jobnumber=$jobid;                  
                $model->ponumber=$jobs->customerpo;
                $model->receiveddate=DateUtil::getDefaultCurrentDateTime();
                $model->receivedtime=DateUtil::getDefaultCurrentTime();
                $model->priority='Normal';
                if($model->save()){
                    return $model;
                }
                
            }
            return NULL;                        
        }
        
}
